import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { SettingsService } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Md5 } from 'ts-md5/dist/md5';

import { AppAuthService, UserService } from '../../services';

@Component({
  selector: 'app-passport-lock',
  templateUrl: './lock.component.html',
  styleUrls: ['./lock.component.less']
})
export class UserLockComponent {
  f: FormGroup;

  _loading = false;

  constructor(
    fb: FormBuilder,
    private auth: AppAuthService,
    public msg: NzMessageService,
    public settings: SettingsService,
    private userSrv: UserService,
    private router: Router
  ) {
    this.f = fb.group({
      password: [null, Validators.required]
    });
    // 标记当前页面为锁定状态
    userSrv.isLockScreen = true;
  }

  get password() {
    return this.f.controls['password'];
  }

  submit() {
    for (const i of Object.keys(this.f.controls)) {
      this.f.controls[i].markAsDirty();
    }
    if (this.f.valid) {
      this._loading = true;
      const body = {
        passWord: Md5.hashStr(this.password.value).toString()
      };
      // this.auth.verifyUserPassWord(body).subscribe(
      //   (response: ApiResToComponent) => {
      //     this._loading = false;
      //     if (response.isComplete && response.items.passWdRight) this.unLockScreen();
      //   }
      // );
    }
  }

  // 确认密码后解锁屏幕
  unLockScreen() {
    this.msg.success('解锁成功！', { nzDuration: 2500 });
    // 关闭路由限制
    this.userSrv.isLockScreen = false;

    // 如果当前的页面包含锁屏页面，则直接跳转主页
    let url = this.userSrv.redirectUrl;
    if (url.includes('/passport') || url.includes('/screen/lock')) {
      url = '/';
    }
    // 跳转路由
    this.router.navigateByUrl(url);
  }
}
